package com.bmslz.monitorpre.grpc;

import com.example.monitor.grpc.*;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.net.ssl.SSLException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class MonitorGrpcClient {

    private ManagedChannel channel;
    private MonitorServiceGrpc.MonitorServiceBlockingStub blockingStub;
    @Value("${grpc.server.server.url}")
    private String serverUrl;
    @Value("${grpc.server.server.port}")
    private Integer port;
    @Value("${client.tls.enable}")
    private boolean tlsEnable;
    @Value("${client.tls.ca}")
    private String ca;
    @Value("${client.project.projectNo}")
    private String projectNo;
    @Value("${client.project.name}")
    private String projectName;
    @Value("${client.project.modelNo}")
    private String modelNo;
    @Value("${client.project.rate}")
    private long projectRate;

    @PostConstruct
    public void init() throws SSLException {
        if (tlsEnable) {
            channel = NettyChannelBuilder.forAddress(serverUrl, port)
                    .sslContext(GrpcSslContexts.forClient()
                            .trustManager(new File(ca))
                            .build())
                    .build();
        } else {
            channel = ManagedChannelBuilder.forAddress(serverUrl, port)
                    .usePlaintext() // 开发环境使用，生产环境应该使用TLS
                    .build();
        }
        blockingStub = MonitorServiceGrpc.newBlockingStub(channel);
    }

    @PreDestroy
    public void shutdown() {
        if (channel != null) {
            channel.shutdown();
        }
    }

    public void sendMetrics(Map<String, String> map) {
        List<MetricsRequest.Metric> metrics = new ArrayList<>();
        for (String key : map.keySet()) {
            metrics.add(MonitorGrpcClient.buildMetric(key, map.get(key),
                    System.currentTimeMillis()));
        }
        sendMetrics(metrics);
    }

    public void sendMetrics(List<MetricsRequest.Metric> metrics) {
        MetricsRequest request = MetricsRequest.newBuilder()
                .setProjectNo(projectNo).setProjectName(projectName).setModelNo(modelNo).setProjectRate(String.valueOf(projectRate))
                .addAllMetrics(metrics)
                .build();

        MetricsResponse response = blockingStub.sendMetrics(request);
        System.out.println("Server response: " + response.getMessage());
    }

    // Metric 辅助构建类
    public static MetricsRequest.Metric buildMetric(String name, String value, long timestamp) {
        return MetricsRequest.Metric.newBuilder()
                .setName(name)
                .setValue(value)
                .setTimestamp(timestamp)
                .build();
    }
}